import { fromPromise } from '../../universalify/index'
import fs from '../fs'
import path from '../../node/path'
import mkdir from '../mkdirs'
import remove from '../remove'
import errorCode from '../../node/error-code'
import { LogUtil } from '../../../LogUtil'

function emptyDir (dir) {
    LogUtil.info('emptyDir');
    return new Promise((res, rej) => {
        try {
            fs.readdir(dir, (e, list) => {
                list.forEach((item)=>{
                    item = path.join(dir,item)
                    remove.remove(item)
                })
                res(true)
            })
        } catch (err) {
            LogUtil.error('fs.readdir error: %{public}s', err.message);
            if (err.message === errorCode.errormessage.ENOTDIR) {
                throw err;
            }
            try {
                mkdir.mkdirs(dir, e => {
                    res(e)
                })
            } catch (err) {
            }
        }
    })
}

function emptyDirSync (dir) {
    try {
        LogUtil.info('emptyDirSync');
        let items
        try {
            items = fs.readdirSync(dir)
        } catch (err) {
            if (err.message === errorCode.errormessage.ENOTDIR) {
                throw err;
            }
            return mkdir.mkdirsSync(dir)
        }

        items.forEach(item => {
            item = path.join(dir, item)
            remove.removeSync(item)
        })
    } catch (e) {
        LogUtil.error('emptyDirSync error: %{public}s', e.message);
    }
}

export default {
    emptyDirSync,
    emptydirSync: emptyDirSync,
    emptyDir: fromPromise(emptyDir),
    emptydir: emptyDir
}
